<?php

namespace App\Http\Controllers\Api;

use App\Constant;
use App\Models\FrontendUser;
use Carbon\Carbon;
use Illuminate\Support\Str;

class PartnerController
{
    /** 自动注册禾只用户 */
    public function hezhiRegister()
    {
        //获取当前用户信息
        /** @var FrontendUser $user */
        $user = auth()->user();
        //获取实名信息
        $auth = $user->auth;
        if (!$auth) {
            return [
                'status' => 'no_auth',
            ];
        }
        $cacheKey = 'hezhi_register:' . $user->mobile;
        if (\Cache::has($cacheKey)) {
            return [
                'status' => 'registered',
            ];
        }
        //注册用户
        $host = config('services.hezhi.host');
        $url = $host . '/apigateway/cr-desk-manage/user/register';
        $password = substr($auth->id_card, -6, 6);
        $idCard = $auth->id_card;
        $data = [
            'lnvitationCode' => config('servicves.hezhi.invitation_code', '999999'),
            'cellphone' => $user->mobile,
            'password' => md5('47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=' . $password),
            'clientIp' => '127.0.0.1',
            'idCard' => [
                'sex' => (0 === substr($idCard, -2, 1) % 2) ? '女' : '男',
                'num' => $idCard,
                'birth' => Carbon::parse(substr($idCard, 6, 8))->format('Y-m-d'),
                'name' => $auth->real_name,
            ],
        ];
        \Log::channel(Constant::LOG_CHANNEL_HEZHI)->info('[IN] USER_REGISTER_RAW_DATA:' . $url, $data);
        $aesEncryptKey = Str::random(16);
        $publicKey = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap('MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCurFBVmUXa0Ov/I9+Whz4YH3/Gbt+QTCMKdDTQ2S4QsWFZ0qvQbBP6JciVDByD/5d/5sHSr9jSgmZPCuXTHmzj9RER3YdylzogQF0tqUQt48U5Cyqsh3yto8XNVoU/H9qr50k+N6YdOT4VGfuRdBovdniyiTMRzYG/UdvxU129CwIDAQAB', 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";
        $body = [
            'requestData' => encrypt_aes(json_encode($data, JSON_UNESCAPED_UNICODE), $aesEncryptKey),
            'encrypted' => encrypt_rsa($aesEncryptKey, $publicKey),
        ];
        \Log::channel(Constant::LOG_CHANNEL_HEZHI)->info('[IN] USER_REGISTER_BODY:' . $url, $body);
        $resp = \Http::asJson()->post($url, $body);
        \Log::channel(Constant::LOG_CHANNEL_HEZHI)->info('[OUT] USER_REGISTER_RESP: ' . $resp->body());
        \Cache::set($cacheKey, 1);

        if ('0' != $resp->json('code')) {
            return [
                'status' => 'register_fail',
            ];
        }

        return [
            'status' => 'register_success',
        ];
    }
}
